﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Net;
using System.Text.RegularExpressions;
using System.Net.Sockets;
using System.Windows.Forms;

namespace SynoManager.DownloadStation.Plugins
{
    [DownloadStationPlugin("Rapid Share", "Automatically authenticate on RapidShare downloads", "Grad van Horck", "1.0")]
    public class RapidSharePlugin : IDownloadUrlHandlerPlugin, IDownloadStationPreferencePanelPlugin
    {
        private DownloadStationService service;
        private string username;
        private string password;

        public RapidSharePlugin()
        {
            username = Properties.Settings.Default.RapidShareUsername;
            password = PasswordHelper.Unprotect(Properties.Settings.Default.RapidSharePassword);
        }

        public string Username
        {
            get { return username; }
            set
            {
                username = value;
                Properties.Settings.Default.RapidShareUsername = value;
            }
        }

        public string Password
        {
            get { return password; }
            set
            {
                password = value;
                Properties.Settings.Default.RapidSharePassword = PasswordHelper.Protect(value);
            }
        }

        public void Process(ProcessUrlArgs args)
        {
            if (String.IsNullOrEmpty(username) || String.IsNullOrEmpty(password))
                return;

            if (args.Url.Host == "rapidshare.com")
            {
                Debug.WriteLine("Processing url " + args.Url, "RapidShare Plugin");

#if !DEBUG
                try {
#endif
                // Determine Rapidshare server
                HttpWebRequest request = (HttpWebRequest) WebRequest.Create(args.Url);
                HttpWebResponse response = (HttpWebResponse) request.GetResponse();
                StreamReader responseStream = new StreamReader(response.GetResponseStream());
                string result = responseStream.ReadToEnd();

                int end = result.IndexOf("." + args.Url.Host + args.Url.PathAndQuery);

                Debug.Assert(end > 0, "Invalid RapidShare URL");
                if (end <= 0)
                {
                    MessageBox.Show("The RapidShare URL could not be downloaded\nPlease check the the supplied URL is valid and still active.\n\nThe link will be ignored.\n\nUrl:\n" + args.Url, "Invalid RapidShare URL", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    // invalid RapidShare URL
                    args.Processed = true;
                    args.Cancel = true;
                    return;
                }

                result = result.Substring(0, end);
                int start = result.LastIndexOf('/');
                Debug.Assert(start > 0);
                string server = result.Substring(start + 1);

                Debug.Assert(server.Length > 0 && server.Length < 20);

                // Create new url
                string url = String.Format("http://{0}:{1}@{2}.rapidshare.com{3}", username, password, server, args.Url.PathAndQuery);
                Debug.WriteLine("URL rewritten to " + url, "RapidShare Plugin");
                service.redirector.AddUrl(url);
                args.Processed = true;
                args.Cancel = true;
#if !DEBUG
                } catch (WebException)
                {
                  // just don't mark it as processed, so it will be added 'pure' to to the download station
                }
#endif
            }
        }

        public void Initialize(DownloadStationService service)
        {
            this.service = service;
        }

        public void Close()
        {
        }

        #region IDownloadStationPreferencePanelPlugin Members

        public SynoManager.GUI.PreferencesPanel PreferencePanel
        {
            get { return new RapidShareOptionsPanel(this); }
        }

        public string PreferenceNodeText
        {
            get { return "RapidShare"; }
        }

        public System.Drawing.Image PreferenceNodeImage
        {
            //TODO: Add Image
            get { return null; }
        }

        #endregion
    }
}
